import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Modal,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  Divider,
  message,
} from 'antd';
import StandardTable from '@components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import AvatarUploader from '../../components/AvatarUploader';
import styles from './TableList.less';

const formCreate = Form.create();
const FormItem = Form.Item;
const { Option } = Select;

const getValue = obj => {
  return Object.keys(obj)
    .map(key => obj[key])
    .join(',');
};

const CreateForm = formCreate(props => {
  const { modalVisible, form, handleSave, handleModalVisible, roleList, originData } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleSave({
        id: originData.id,
        ...fieldsValue,
      });
    });
  };

  const isAdd = !originData.id;

  return isAdd ? (
    <Modal
      title="添加用户"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="用户名">
        {form.getFieldDecorator('username', {
          rules: [{ required: isAdd, message: '请输入用户名.' }],
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="密码">
        {form.getFieldDecorator('password', {
          rules: [{ required: isAdd, message: '请输入密码.' }],
        })(<Input placeholder="请输入" type="password" />)}
      </FormItem>
    </Modal>
  ) : (
    <Modal
      title="添加用户"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="头像">
        {form.getFieldDecorator('avatar', {
          initialValue: originData.avatar,
          rules: [{ required: false, message: '请选择头像' }],
        })(<AvatarUploader className={styles.cover} />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="昵称">
        {form.getFieldDecorator('nickName', {
          initialValue: originData.nick_name,
          rules: [{ required: true, message: '请输入昵称.' }],
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="邮箱">
        {form.getFieldDecorator('email', {
          initialValue: originData.email,
          rules: [{ required: true, message: '请输入邮箱.' }],
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="年龄">
        {form.getFieldDecorator('age', {
          initialValue: originData.age,
          rules: [{ required: true, message: '请输入年龄.' }],
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="角色">
        {form.getFieldDecorator('roleId', {
          initialValue: originData.role_id,
          rules: [{ required: true, message: '请选择角色.' }],
        })(
          <Select style={{ width: '100%' }} placeholder="请选择">
            {roleList.map(item => <Option key={item.id}>{item.name}</Option>)}
          </Select>
        )}
      </FormItem>
    </Modal>
  );
});
@connect(({ user, role, loading }) => ({
  user,
  role,
  loading: loading.models.user,
}))
@formCreate
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    originData: {},
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'user/fetch',
    });
    dispatch({
      type: 'role/fetch',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'user/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'user/fetch',
      payload: {},
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;

    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'article/remove',
          payload: {
            ids: selectedRows.map(row => row.id),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
            dispatch({
              type: 'user/fetch',
            });
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'user/fetch',
        payload: values,
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleSave = fields => {
    const { dispatch } = this.props;
    const { id } = fields;
    if (id) {
      dispatch({
        type: 'user/update',
        payload: {
          id,
          avatar: fields.avatar,
          nickName: fields.nickName,
          email: fields.email,
          age: fields.age,
          roleId: fields.roleId,
        },
      });
    } else {
      dispatch({
        type: 'user/add',
        payload: {
          username: fields.username,
          password: fields.password,
          code: '2018',
        },
      });
    }
    message.success('保存成功');
    this.setState({
      modalVisible: false,
    });
    dispatch({
      type: 'user/fetch',
    });
  };

  handleNewClick = () => {
    this.setState({
      originData: {},
    });
    this.handleModalVisible(true);
  };

  handleEditClick = (id, record) => {
    this.setState({
      originData: record,
    });
    this.handleModalVisible(true);
  };

  renderForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="账号">
              {getFieldDecorator('userName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="昵称">
              {getFieldDecorator('nickName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const { user: { data }, role, loading } = this.props;
    const { selectedRows, modalVisible, originData } = this.state;
    const columns = [
      {
        title: '账号',
        dataIndex: 'user_name',
        width: 300,
        render: val => <div className={styles.abstract}>{val}</div>,
      },
      {
        title: '昵称',
        dataIndex: 'nick_name',
        render: val => <div>{val}</div>,
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        render: val => <span>{val}</span>,
      },
      {
        title: '创建时间',
        dataIndex: 'created_at',
        sorter: true,
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
      },
      {
        title: '操作',
        dataIndex: 'id',
        render: (val, record) => (
          <Fragment>
            <a>查看</a>
            <Divider type="vertical" />
            <a onClick={() => this.handleEditClick(val, record)}>编辑</a>
          </Fragment>
        ),
        width: 200,
      },
    ];

    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
        <Menu.Item key="approval">批量审批</Menu.Item>
      </Menu>
    );

    const parentProps = {
      modalVisible,
      originData,
      roleList: role.data.list,
      handleSave: this.handleSave,
      handleModalVisible: this.handleModalVisible,
    };

    return (
      <PageHeaderLayout>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleNewClick()}>
                新建
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  {/* <Button>批量操作</Button> */}
                  <Dropdown overlay={menu}>
                    <Button>
                      更多操作 <Icon type="down" />
                    </Button>
                  </Dropdown>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm {...parentProps} />
      </PageHeaderLayout>
    );
  }
}
